package com.yunchao.test.data.repository

import com.yunchao.feature.base.domain.result.andThen
import com.yunchao.feature.base.domain.result.createException
import com.yunchao.library.lock.DeviceHelper
import com.yunchao.library.lock.IDeviceHelper
import com.yunchao.library.lock.LockEPCInfo
import com.yunchao.test.domain.model.LockToolModel
import com.yunchao.test.domain.model.VoucherTypeModel
import com.yunchao.test.domain.repository.LockToolRepository
import com.yunchao.test.domain.repository.MaintenanceInfoRepository
import java.time.LocalDate
import java.time.format.DateTimeFormatter
import java.time.temporal.ChronoUnit

internal class LockToolRepositoryImpl(
    private val deviceHelper: DeviceHelper,
    private val maintenanceInfoRepository: MaintenanceInfoRepository
) : LockToolRepository {
    override suspend fun openDevice(): Result<Boolean> = runCatching {
        deviceHelper.openEmbededDevice()
    }

    override suspend fun closeDevice() {
        deviceHelper.closeDevice()
    }

    override suspend fun inventoryOnce(): Result<LockToolModel> = runCatching {
        deviceHelper.inventoryOnce()
    }.andThen { lockEpcInfo ->
        val maintenanceInfoModel =
            maintenanceInfoRepository.getMaintenanceInfoByLockNo(lockEpcInfo.id).getOrNull()



        maintenanceInfoModel?.let {
            // 去除双引号
            val cleanDateStr = it.warrantyPeriod.replace("\"", "")
            // 定义日期格式
            val formatter = DateTimeFormatter.ofPattern("yyyy年M月d日")
            // 将处理后的目标日期字符串解析为 LocalDate 对象
            val targetDate = LocalDate.parse(cleanDateStr, formatter)
            // 获取当前日期
            val currentDate = LocalDate.now()
            // 计算目标日期到当前日期的天数差
            val daysDifference = ChronoUnit.DAYS.between(currentDate, targetDate)

            if (daysDifference >= 0) {
                Result.success(LockToolModel(handleBeforeLockEPCInfo = lockEpcInfo))
            }else{
                Result.success(LockToolModel(handleBeforeLockEPCInfo = lockEpcInfo, message = "锁号：${lockEpcInfo.id} 已过维保期"))
            }
        } ?: Result.success(
            LockToolModel(
                handleBeforeLockEPCInfo = lockEpcInfo,
                message = "锁号：${lockEpcInfo.id} 未登记"
            )
        )
    }

    override suspend fun activeLock(
        lockEPCInfo: LockEPCInfo,
        voucherType: VoucherTypeModel
    ): Result<LockToolModel> = runCatching {
        val result = deviceHelper.activateLock(
            lockEPCInfo = lockEPCInfo,
            deviceId = IDeviceHelper.DEFAULT_DEVICE_ID,
            operatorId = IDeviceHelper.DEFAULT_OPERATOR_1,
            chkUserId = IDeviceHelper.DEFAULT_OPERATOR_2,
            pageNumber = 0,
            voucherType = voucherType.voucherType
        )
        LockToolModel(handleBeforeLockEPCInfo = lockEPCInfo, handleAfterLockEPCInfo = result)
    }

    override suspend fun openLockWriteLogistics(lockEPCInfo: LockEPCInfo): Result<LockToolModel> =
        runCatching {
            val result = deviceHelper.openLockWriteLogistics(
                lockEPCInfo = lockEPCInfo,
                deviceId = IDeviceHelper.DEFAULT_DEVICE_ID,
                operatorId = IDeviceHelper.DEFAULT_OPERATOR_1,
                chkUserId = IDeviceHelper.DEFAULT_OPERATOR_2,
                pageNumber = 0
            )
            LockToolModel(handleBeforeLockEPCInfo = lockEPCInfo, handleAfterLockEPCInfo = result)
        }

    override suspend fun closeLockWriteLogistics(lockEPCInfo: LockEPCInfo): Result<LockToolModel> =
        runCatching {
            val result = deviceHelper.closeLockWriteLogistics(
                lockEPCInfo = lockEPCInfo,
                deviceId = IDeviceHelper.DEFAULT_DEVICE_ID,
                operatorId = IDeviceHelper.DEFAULT_OPERATOR_1,
                chkUserId = IDeviceHelper.DEFAULT_OPERATOR_2,
                pageNumber = IDeviceHelper.DEFAULT_PAGE_NUMBER
            )
            LockToolModel(handleBeforeLockEPCInfo = lockEPCInfo, handleAfterLockEPCInfo = result)
        }

    override suspend fun openLock(lockEPCInfo: LockEPCInfo): Result<LockToolModel> = runCatching {
        val result = deviceHelper.openLock(
            lockEPCInfo = lockEPCInfo,
            deviceId = IDeviceHelper.DEFAULT_DEVICE_ID,
            operatorId = IDeviceHelper.DEFAULT_OPERATOR_1,
            chkUserId = IDeviceHelper.DEFAULT_OPERATOR_2,
            pageNumber = 0
        )
        LockToolModel(handleBeforeLockEPCInfo = lockEPCInfo, handleAfterLockEPCInfo = result)
    }

    override suspend fun closeLock(lockEPCInfo: LockEPCInfo): Result<LockToolModel> = runCatching {
        val result = deviceHelper.closeLock(
            lockEPCInfo = lockEPCInfo,
            deviceId = IDeviceHelper.DEFAULT_DEVICE_ID,
            operatorId = IDeviceHelper.DEFAULT_OPERATOR_1,
            chkUserId = IDeviceHelper.DEFAULT_OPERATOR_2,
            pageNumber = IDeviceHelper.DEFAULT_PAGE_NUMBER
        )
        LockToolModel(handleBeforeLockEPCInfo = lockEPCInfo, handleAfterLockEPCInfo = result)
    }

    override suspend fun recoveryLock(lockEPCInfo: LockEPCInfo): Result<LockToolModel> =
        runCatching {
            val result = deviceHelper.recoveryLock(
                lockEPCInfo = lockEPCInfo,
                deviceId = IDeviceHelper.DEFAULT_DEVICE_ID,
                operatorId = IDeviceHelper.DEFAULT_OPERATOR_1,
                chkUserId = IDeviceHelper.DEFAULT_OPERATOR_2
            )
            LockToolModel(handleBeforeLockEPCInfo = lockEPCInfo, handleAfterLockEPCInfo = result)
        }

    override suspend fun cleanLock(lockEPCInfo: LockEPCInfo): Result<LockToolModel> =
        runCatching {
            val result = deviceHelper.cleanLockLog(
                lockEPCInfo = lockEPCInfo,
                deviceId = IDeviceHelper.DEFAULT_DEVICE_ID,
                operatorId = IDeviceHelper.DEFAULT_OPERATOR_1,
                chkUserId = IDeviceHelper.DEFAULT_OPERATOR_2,
                pageNumber = lockEPCInfo.pageNumber
            )
            LockToolModel(handleBeforeLockEPCInfo = lockEPCInfo, handleAfterLockEPCInfo = result)
        }


    override suspend fun readLockLogisticsLog(lockEPCInfo: LockEPCInfo): Result<LockToolModel> =
        runCatching {
            val result = deviceHelper.readLockLogisticsLog(lockEPCInfo)
            LockToolModel(
                handleBeforeLockEPCInfo = lockEPCInfo,
                handleAfterLockEPCInfo = lockEPCInfo,
                lockLogList = result
            )
        }

    override suspend fun readLockLogCount(lockEPCInfo: LockEPCInfo): Result<LockToolModel> =
        runCatching {
            val result = deviceHelper.readLockLogCount(lockEPCInfo)
            LockToolModel(
                handleBeforeLockEPCInfo = lockEPCInfo,
                handleAfterLockEPCInfo = lockEPCInfo,
                loggerTotalCount = result
            )
        }

    override suspend fun readLockLog(
        lockEPCInfo: LockEPCInfo,
        start: Int,
        number: Int
    ): Result<LockToolModel> = runCatching {
        val result =
            deviceHelper.readLockLog(lockEPCInfo = lockEPCInfo, start = start, number = number)
        LockToolModel(
            handleBeforeLockEPCInfo = lockEPCInfo,
            handleAfterLockEPCInfo = result.first,
            lockLogList = result.second
        )
    }
}